﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class TeacherDetails : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var itemId = Request["itid"];
            var teacher = TeacherServices.GetById(new Guid(itemId));

            ltrName.Text = teacher.Name;
            //ltrSubject.Text = SubjectServices.GetById(Convert.ToInt16(teacher.Subject.Split(',')[0])).Name;
            prfPic.ImageUrl = teacher.ImagePath;
            ltrRate.NumberStar = teacher.Rate;

            string subjects = SubjectServices.GetSubjects(teacher.Subject).Aggregate(string.Empty, (current, sb) => current + (sb.Name + ",&nbsp"));
            if (!string.IsNullOrEmpty(subjects)) subjects = subjects.Substring(0, subjects.Length - 6);

            ltrTeach.Text = subjects;
            ltrSubject.Text = subjects;

            ltrAddress.Text = string.Format("{0}, {1}", teacher.District, teacher.City);
            ltrAge.Text = (teacher.Age == 0) ? "Chưa cập nhật" : teacher.Age.ToString();
            ltrFees.Text = (teacher.Fees == 0) ? "Thỏa thuận" : teacher.Fees.ToString();
            ltrAvailability.Text = string.IsNullOrEmpty(teacher.Availability) ? "Chưa cập nhật" : teacher.Availability;
            ltrNumberFb.Text = (teacher.Feedbacks.Count <= 0) ? "Chưa có phản hồi từ học viên" : string.Format(ltrNumberFb.Text, teacher.Feedbacks.Count);
            ltrProfile.Text = string.IsNullOrEmpty(teacher.Discribe) ? teacher.Intro : teacher.Discribe;

            trAccept.Visible = !(string.IsNullOrEmpty(Request["ctreqid"]));
            rptFeedback.Visible = (teacher.Feedbacks.Count > 0);
            if (teacher.Feedbacks.Count <= 0) return;
            rptFeedback.DataSource = teacher.Feedbacks;
            rptFeedback.DataBind();
        }

        protected void BtnAcceptContactClick(object sender, EventArgs e)
        {
            var ctedId = new Guid(Request["ctreqid"]);
            ContactedRequest contactedRequest = ContactedRequestServices.GetContactedRequest(ctedId);

            SendAcceptEmail(contactedRequest);
            SendStudentAcceptEmail(contactedRequest);
            SenRefuseEmail(contactedRequest);

            StudentRequest studentRequest = StudentRequestServices.GetById(contactedRequest.Request.ID);
            studentRequest.IsClosed = true;
            StudentRequestServices.SaveOrUpdate(studentRequest);
        }

        #region Private Methods
        private void SendAcceptEmail(ContactedRequest contactedRequest)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["AcceptContact"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            var teachSubject = SubjectServices.GetById(Convert.ToInt16(contactedRequest.Request.Subject)).Name;
            var urlPostRequest = string.Format("{0}/StudentRequestDetails.aspx?itid={1}", SiteUrl, contactedRequest.Request.ID);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.AcceptContactEmailBuilder(Convert.ToString(rows[0]["Content"]), contactedRequest.Teacher.Name,
                contactedRequest.Teacher.Name, teachSubject, urlPostRequest, contactedRequest.Request.Title);

            EmailSender.SendMail(subject, contentMail, contactedRequest.Teacher.Email);
        }

        private void SenRefuseEmail(ContactedRequest contactedRequest)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["RefuseContact"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            var urlPostRequest = string.Format("{0}/StudentRequestDetails.aspx?itid={1}", SiteUrl, contactedRequest.Request.ID);
            IList<Teacher> ctedTeachers = ContactedRequestServices.GetContactedTeachers(contactedRequest.Teacher.ID);
            foreach (Teacher ctedTeacher in ctedTeachers)
            {
                NVelocityBuilder.SetResourcePath(tmpPath);
                var contentMail = NVelocityBuilder.RefuseContactEmailBuilder(Convert.ToString(rows[0]["Content"]), ctedTeacher.Name,
                    contactedRequest.Request.Name, contactedRequest.Teacher.Name, urlPostRequest, contactedRequest.Request.Title);

                EmailSender.SendMailAsync(subject, contentMail, ctedTeacher.Email);
            }
        }

        private void SendStudentAcceptEmail(ContactedRequest contactedRequest)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["StudentAccept"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            var feedbackUrl = string.Format("{0}/StudentFeedback.aspx?ctreqid={1}", SiteUrl, contactedRequest.ID);
            var contactInfo = contactedRequest.Teacher.IsContactEmail
                                  ? string.Format("Điện thoại: {0}", contactedRequest.Teacher.PhoneNumber)
                                  : string.Format("Email: {0}", contactedRequest.Teacher.Email);
            var teacherAddress = string.Format("{0}, {1}, {2}", contactedRequest.Teacher.Address, contactedRequest.Teacher.District, contactedRequest.Teacher.City);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.AcceptedStudentEmailBuider(Convert.ToString(rows[0]["Content"]), contactedRequest.Request.Name
                , contactedRequest.Teacher.Name, contactInfo, teacherAddress, feedbackUrl);

            EmailSender.SendMail(subject, contentMail, contactedRequest.Request.Email);
        }
        #endregion
    }
}
